<template>
  <div class="login-container">
    <!-- 登入导航栏 -->
    <van-nav-bar
      title="登入"
      left-text="返回"
      left-arrow
      @click-left="$router.back()"
    />

    <!-- 表单输入框 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="mobile"
        name="mobile"
        label="手机号"
        placeholder="请输入手机号"
        required
        :rules="[
          { required: true, message: '请填写用户名' },
          {
            pattern:
              /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '手机号格式不对',
          },
        ]"
      />
      <van-field
        v-model="code"
        name="code"
        label="验证码"
        placeholder="验证码"
        required
        :rules="[
          { required: true, message: '请填写密码' },
          { pattern: /^\d{6}$/, message: '验证码格式不对' },
        ]"
      />
      <div style="margin: 16px">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          loading-text="加载中..."
          :loading="isLogin"
          :disabled="isLogin"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
// 导入登入请求接口
import { userLogin } from "./user.js";

// 导入token先关接口
import { saveToken } from "@/utils/token.js";

export default {
  name: "login",
  data() {
    return {
      mobile: "15012345678",
      code: "246810",
      isLogin: false,
    };
  },
  methods: {
    onSubmit(values) {
      this.isLogin = true;
      userLogin(values)
        // 登入成功
        .then((ret) => {
          // 轻弹窗
          this.$toast({
            message: "登入成功",
            icon: "like-o",
          });

          // 将token存到本地
          let token = ret.data.data;
          saveToken(token);
          // 跳转首页
          this.$router.push({ path: "/home" });
        })
        // 登入失败
        .catch((err) => {
          this.$toast({
            message: "账户或验证码错误",
            icon: "close",
          });
        })
        .then(() => {
          this.isLogin = false;
        });
    },
  },
};
</script>

<style lang='less'>
.login-container {
  .van-nav-bar__content {
    background-color: #0098fa;
    .van-nav-bar__title,
    .van-nav-bar__text,
    .van-icon {
      color: white;
    }
  }
}
</style>